package com.hnkywl.sts.dao.organ;

import com.hnkywl.sts.dao.sys.YgDao;
import com.hnkywl.sts.entity.organ.Ck;
import com.hnkywl.sts.entity.organ.Gsjg;
import com.hnkywl.sts.entity.organ.Nbbm;
import com.hnkywl.sts.entity.sys.Yg;
import com.hnkywl.sts.service.sys.YgService;
import net.ruixin.orm.hibernate.Page;
import net.ruixin.orm.hibernate.SimpleHibernateTemplate;
import org.hibernate.Criteria;
import org.hibernate.Hibernate;
import org.hibernate.criterion.*;
import org.hibernate.type.Type;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import java.util.ArrayList;
import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: jerry
 * Date: 13-3-28
 * Time: 下午3:27
 * To change this template use File | Settings | File Templates.
 */
@Repository
public class CkDao extends SimpleHibernateTemplate<Ck, Long> {
    private YgDao ygDao;
    private GsjgDao gsjgDao;

    /**
     * 查询仓库列表
     *
     * @param ckmc     仓库名称
     * @param ssgsjg   所属公司机构
     * @param pageNo
     * @param pageSize
     * @return
     */
    public Page<Ck> findCkList(String ckmc, String ssgsjg, String nbgsIds, int pageNo, int pageSize) {
        String hql = null;
        List<Object> param = new ArrayList<Object>();
        StringBuilder condition = new StringBuilder();
        Page<Ck> page = new Page<Ck>(pageNo, pageSize, 0);
        //==============条件拼接===============
        if (ckmc != null && !ckmc.isEmpty()) {
            if (condition.length() != 0)
                condition.append(" and ");
            condition.append(" mc like ? ");
            param.add("%" + ckmc.trim() + "%");
        }
        if (!nbgsIds.equals("")) {
            if (condition.length() != 0)
                condition.append(" and ");
            condition.append("ssgsjg.id in (" + nbgsIds + ") ");
        }
        if (nbgsIds.equals("") && ssgsjg != null) {
            if (condition.length() != 0)
                condition.append(" and ");
            condition.append(" ssgsjg.qc like ? ");
            param.add("%" + ssgsjg.trim() + "%");
        }
        //==============记录数量===============
        hql = "select count(*) from Ck";
        if (condition.length() != 0)
            hql = hql + " where " + condition;
        Long c = null;
        if (param.size() != 0) {
            c = (Long) findUnique(hql, param.toArray());
            page.setTotalCount(c.intValue());
        } else {
            c = (Long) findUnique(hql);
            page.setTotalCount(c.intValue());
        }
        if (c == 0)
            return page;
        //==============查询结果===============
        hql = "from Ck ";
        if (condition.length() != 0)
            hql = hql + " where " + condition;
        hql = hql + " order by dateCreated desc";
        if (param.size() != 0)
            return find(page, hql, param.toArray());
        return find(page, hql);
    }

    public List findCkList(Long ssgsjgId) {
        Yg yg = ygDao.get(YgService.getCurrentYg().getId());
        List<Long> gsIdList = new ArrayList<Long>();
        for (Gsjg gsjg : yg.getSsjgList()) {
            gsIdList.add(gsjg.getId());
        }

        DetachedCriteria detachedCriteria = DetachedCriteria.forClass(Gsjg.class);

        detachedCriteria.createAlias("sjjg", "sjjg", CriteriaSpecification.LEFT_JOIN)
                .setProjection(Projections.projectionList()
                        .add(Property.forName("sjjg.id").as("sjjg.id")))
                .add(Restrictions.in("id", gsIdList));

        Criteria critera = this.getSession().createCriteria(this.entityClass)
                .setProjection(Projections.projectionList()
                        .add(Property.forName("id").as("id"))
                        .add(Property.forName("mc").as("mc"))
                        .add(Projections.sqlProjection("this_.ckjb as ckjb", new String[]{"ckjb"}, new Type[]{Hibernate.LONG})))
                .setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
                .add(Restrictions.or(Property.forName("ssgsjg.id").in(detachedCriteria), Restrictions.in("ssgsjg.id", gsIdList)))
                .add(Restrictions.ne("ckjb", 3));
        return critera.list();
    }

    public List findBgCkList() {
        Criteria critera = this.getSession().createCriteria(this.entityClass)
                .setProjection(Projections.projectionList()
                        .add(Property.forName("id").as("id"))
                        .add(Projections.sqlProjection("this_.mc as mc", new String[]{"mc"}, new Type[]{Hibernate.STRING}))
                        .add(Projections.sqlProjection("this_.ckjb as ckjb", new String[]{"ckjb"}, new Type[]{Hibernate.LONG})))
                .setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
                .add(Restrictions.or(Restrictions.eq("mc", "丁集供应组"), Restrictions.eq("mc", "铁运公司供应站")))
                .add(Restrictions.ne("ckjb", 3));
        return critera.list();
    }

    public List findYwsfcCkList() {
        Criteria critera = this.getSession().createCriteria(this.entityClass)
                .setProjection(Projections.projectionList()
                        .add(Property.forName("id").as("id"))
                        .add(Projections.sqlProjection("this_.mc as mc", new String[]{"mc"}, new Type[]{Hibernate.STRING}))
                        .add(Projections.sqlProjection("this_.ckjb as ckjb", new String[]{"ckjb"}, new Type[]{Hibernate.LONG})))
                .setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
                        //.add(Restrictions.or(Restrictions.eq("mc", "丁集供应组"), Restrictions.eq("mc", "铁运公司供应站")))
                .add(Restrictions.ne("ckjb", 3));
        return critera.list();
    }


    public List findCkSearch(Long ssgsjgId) {
        if (ssgsjgId == null)
            ssgsjgId = YgService.getCurrentYgZgGsId();
        Criteria critera = this.getSession().createCriteria(this.entityClass)
                .setProjection(Projections.projectionList()
                        .add(Property.forName("id").as("id"))
                        .add(Property.forName("mc").as("mc")))
                .setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
                .add(Restrictions.or(Restrictions.eq("ssgsjg.id", ssgsjgId), Restrictions.eq("ssgsjg.id", YgService.getCurrentYgZgGsId())))
                .add(Restrictions.ne("ckjb", 3));
        return critera.list();
    }

    public List sskcCkmcForSskc(Long ssgsjgId) {
        if (ssgsjgId == null) {
            ssgsjgId = YgService.getCurrentYgZgGsId();
        } else {
            Gsjg ckgs = gsjgDao.get(ssgsjgId);
            if (ckgs.className().equals("Nbbm")) {
                if ((((Nbbm) ckgs).getSfgyz() == null || !((Nbbm) ckgs).getSfgyz())
                        && ((Nbbm) ckgs).getKhckList() != null
                        && ((Nbbm) ckgs).getKhckList().size() > 0) {

                    Criteria critera = this.getSession().createCriteria(this.entityClass)
                            .createAlias("ssbmList", "ssbmList", Criteria.LEFT_JOIN)
                            .setProjection(Projections.projectionList()
                                    .add(Property.forName("id").as("id"))
                                    .add(Property.forName("mc").as("mc")))
                            .setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
                            .add(Restrictions.eq("ssbmList.id", ckgs.getId()))
                            .add(Restrictions.ne("ckjb", 3)).add(Restrictions.ne("sfzx", false));
                    return critera.list();
                } else
                    ssgsjgId = ckgs.getSjjg().getId();
            }
        }
        Criteria critera = this.getSession().createCriteria(this.entityClass)
                .setProjection(Projections.projectionList()
                        .add(Property.forName("id").as("id"))
                        .add(Property.forName("mc").as("mc")))
                .setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
                .add(Restrictions.eq("ssgsjg.id", ssgsjgId))
                .add(Restrictions.ne("ckjb", 3)).add(Restrictions.ne("sfzx", false));
        return critera.list();
    }

    public List findCkSearchForSearch(Long ssgsjgId) {
        if (ssgsjgId == null) {
            ssgsjgId = YgService.getCurrentYgZgGsId();
        } else {
            Gsjg ckgs = gsjgDao.get(ssgsjgId);
            if (ckgs.className().equals("Nbbm")) {
                ssgsjgId = ckgs.getSjjg().getId();
            }
        }
        Criteria critera = this.getSession().createCriteria(this.entityClass)
                .setProjection(Projections.projectionList()
                        .add(Property.forName("id").as("id"))
                        .add(Property.forName("mc").as("mc")))
                .setResultTransformer(CriteriaSpecification.ALIAS_TO_ENTITY_MAP)
                .add(Restrictions.eq("ssgsjg.id", ssgsjgId))
                .add(Restrictions.ne("ckjb", 3)).add(Restrictions.ne("sfzx", false));
        return critera.list();
    }

    /**
     * 判断属性是否重复
     *
     * @param id            仓库id
     * @param propertyName  仓库属性名
     * @param propertyValue 仓库属性值
     * @return
     */
    public Boolean checkUnique(Long id, String propertyName, Object propertyValue) {
        String hql;
        if (propertyValue == null)
            return false;
        if (id == null) {
            //修改检验
            hql = "from Ck where " + propertyName + " = ? ";
            return this.existsQuery(hql, propertyValue);
        } else {
            //新增检验
            hql = "from Ck where " + propertyName + " = ? and id <>?";
            return this.existsQuery(hql, propertyValue, id);
        }
    }

    /**
     * 查找最大排序号
     *
     * @return
     */
    public Integer findMaxPxh() {
        String hql = "select Max(pxh) from Ck";
        return findInt(hql);
    }

    public Ck findByMc(String name) {
        String hql = "select ck from Ck ck where ck.mc = ?";
        return (Ck) findUnique(hql, name);
    }

    public Ck findByBh(String bh) {
        String hql = "select ck from Ck ck where ck.bh = ?";
        return (Ck) findUnique(hql, bh.trim());
    }

    /**
     * 根据仓库名称查询仓库并返回
     * @param mc
     * @return
     */
    public Ck findCkByMc(String mc){
        String hql = "select ck from Ck ck where ck.mc = ?";
        List<Ck> list = find(hql,mc);
        if (list!=null&& list.size()>0){
            return list.get(0);
        }
        return null;
    }

    @Autowired
    public void setYgDao(YgDao ygDao) {
        this.ygDao = ygDao;
    }

    @Autowired
    public void setGsjgDao(GsjgDao gsjgDao) {
        this.gsjgDao = gsjgDao;
    }
}
